﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using DLM.Web.MVC.Models;
using DLM.Domain.Model;
using DLM.Services.Interfaces;
using DLM.Web.ViewModel;
using Microsoft.Web.Helpers;
using Webdiyer.WebControls.Mvc;
using DLM.Infrastructure.Security;
using DLM.Services.Implementations;
using DLM.Infrastructure.Email;
using DLM.Web.MVC.Extensions;

namespace DLM.Web.MVC.Controllers
{
    public class AccountController : BaseController
    {

        private IUserService userService;
        private IEmailService mailService;

        public AccountController(IUserService userService,IEmailService mailService)
        {
            this.userService = userService;
            this.mailService = mailService;
        }

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [ValidateMvcCaptcha]
        public ActionResult Login(Account account)
        {
            try
            {
                //var captchaSuccess = ReCaptcha.Validate("6LdYRtESAAAAAInpSF9yl6Z2awmd8-hYgXfc7Rvg");
                //if (!captchaSuccess)
                //{
                //    ModelState.AddModelError("", "验证码输入错误！");
                //    return View();
                //}
                if (ModelState["_mvcCaptchaText"] != null && ModelState["_mvcCaptchaText"].Errors.Count > 0)
                {
                    ModelState.AddModelError("", "验证码不匹配，请重新输入！");
                    return View();
                }
                userService.Login(account);
                if (Request.QueryString["ReturnUrl"] != null)
                {
                    this.Response.Redirect(Request.QueryString["ReturnUrl"]);
                }
                return RedirectToAction("Default", "Home");
            }
            catch (ArgumentNullException)
            {
                ModelState.AddModelError("AccountName", "账户不允许为空！");
                return View();
            }
            catch (System.Security.Authentication.InvalidCredentialException)
            {
                ModelState.AddModelError("AccountName", "账户或者密码错误！");
                return View();
            }
            catch (System.Security.Authentication.AuthenticationException)
            {
                return RedirectToAction("UnActivated", new { account = account.AccountName });
                // return View("Activation");
            }
            catch (DLM.Infrastructure.Exception.AccountNotValidateException)
            {
                ModelState.AddModelError("AccountName", "账户已经系统加入黑名单，请联系管理员");
                return View();
            }
            return View();

        }

        [HttpGet]
        public ActionResult UnActivated(string account)
        {
            var current = this.userService.GetAccount(account);
            return View(current);
        }

        [HttpPost]
        public ActionResult Activate(int id)
        {
            var current = this.userService.GetAccount(id);
            MailService service = new MailService(this.mailService);
            service.SendRegisterNotice(current);
            return View("UnActivated", current);
        }

        [HttpGet]
        public ActionResult Activated()
        {

            return View();
        }

        [HttpGet]
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        [ValidateMvcCaptcha]
        public ActionResult Register(AccountPageView pageView, CountrySelectionPageView cuountryView, NativeSelectionPageView nativeView,FormCollection collection)
        {
            try
            {
                if (ModelState["_mvcCaptchaText"] != null && ModelState["_mvcCaptchaText"].Errors.Count > 0)
                {
                    ModelState.AddModelError("", "验证码不匹配，请重新输入！");
                    return View(pageView);
                }
                if (string.IsNullOrEmpty(collection["User.Gender"]))
                {
                    ModelState.AddModelError("", "请选择性别");
                    return View(pageView);
                }
                if (string.IsNullOrEmpty(collection["User.Marriage"]))
                {
                    ModelState.AddModelError("", "请选择婚姻状况");
                    return View(pageView);
                }
                Account account = pageView.Account;
                if (pageView.ConfirmedPassword != pageView.Account.Password)
                {
                    ModelState.AddModelError("Account.Password", "输入的密码不一致！");
                    return View(pageView);
                }
                var user = this.userService.GetAccount(pageView.Account.AccountName);
                if (user != null)
                {

                    ModelState.AddModelError("Account.AccountName", "该昵称已经存在！");
                    return View();
                }

                var email = this.userService.GetAccountByEmail(pageView.Account.Email);
                if (email != null)
                {
                    ModelState.AddModelError("Account.AccountName", "该邮箱已经被注册过了");
                    return View(pageView);
                }


                // User user = pageView.User;
                List<User> userList = new List<User>();
                //pageView.User.Gender = (collection["User.Gender"].ToString() == "0") ? false : true;
                //pageView.User.Marriage = (collection["User.Marriage"].ToString() == "0") ? false : true;
                pageView.User.Location = (cuountryView.SelectedProvince + " " + cuountryView.SelectedCity + " " + cuountryView.SelectedZone).Trim();
                if (string.IsNullOrEmpty(pageView.User.Location))
                {
                    ModelState.AddModelError("Account.AccountName", "请选择现居住地！");
                    return View(pageView);
                }
                pageView.User.NativePlace = (nativeView.SelectedNativeProvince + " " + nativeView.SelectedNativeCity + " " + nativeView.SelectedNativeZone).Trim();
                userList.Add(pageView.User);
                account.Users = userList;
                this.userService.AddAccount(account);
                return RedirectToAction("UnActivated", new { account = account.AccountName });
            }
            catch (System.Net.Mail.SmtpException)
            {
                ModelState.AddModelError("", "激活邮件发送失败，请联系管理员或者重试");
                return View(pageView);
            }
            catch (Exception ex)
            {

                ModelState.AddModelError("", "注册失败，请重试或者联系管理员");
                return View(pageView);
            }   
            return View();

        }

        [HttpGet]
        [UserAuthorize]
        public ActionResult ChangePassword()
        {
            Account account = this.userService.GetAccount(User.Identity.Name);
            return View(account);
        }


        [HttpPost]
        [UserAuthorize]
        public ActionResult ChangePassword(Account account,FormCollection collection)
        {
            var confirmedPass = collection["txtConfirmedPass"].ToString();
            if (account.Password == confirmedPass)
            {
                try
                {
                    var currentAccount = this.userService.GetAccount(account.AccountID);
                    if (currentAccount != null)
                    {
                        currentAccount.Password = Md5Encrypt.HashPassword(account.Password);
                        currentAccount.Email = account.Email;
                        this.userService.UpdateAccount(currentAccount);
                        return View("_AccountInfo", currentAccount);
                    }
                }
                catch (Exception ex)
                {

                    ModelState.AddModelError("",ex.Message);
                    return View("_AccountInfo", account);
                }

            }
            else
            {
                //ModelState.AddModelError("Password", "两次输入的密码不一致，请检查！");
                Response.StatusCode = 500;
                return Content("两次输入的密码不一致");
            }
            return View("_AccountInfo",account);
        }

        [HttpGet]
        public ActionResult LogOff()
        {
            this.userService.LogOut();
            return RedirectToAction("Index", "Home");
        }

        [HttpGet]
        public ActionResult Activation()
        {
            string code = Request.QueryString["code"] == null ? string.Empty:Request.QueryString["code"].ToString();
            this.userService.Activate(code);
            return RedirectToAction("Login","Account");
        }

        [HttpGet]
        [OutputCache(Duration=int.MaxValue,VaryByParam="None")]
        public ActionResult ShowRegisterNotice()
        {
            return PartialView("_RegisterNotice");
        }

        [HttpGet]
        public ActionResult RetrievePassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult RetrievePassword(Account account)
        {
            var current = this.userService.GetAccount(account.AccountName);
            if (current == null)
            {
                ModelState.AddModelError("Email", "邮箱和账户不匹配");
                return View();
            }

            if (current.Email != account.Email)
            {
                ModelState.AddModelError("Email", "邮箱和账户不匹配");
                return View();
            }

            current.ActiveCode = Guid.NewGuid().ToString();
            this.userService.UpdateAccount(current);
            MailService mailService = new MailService(this.mailService);
            mailService.SendRetrievePasswordNotice(current);
            TempData["Message"] = "请到填写的邮箱收取邮件";
            return View();
        }

        [HttpGet]
        public ActionResult ResetPassword(string code)
        {
            var account = this.userService.GetAccountByCode(code);
            if (account == null)
            {
                return View("Error");
            }
            ResetPasswordPageView view = new ResetPasswordPageView 
            {
                Code = code
            };
            return View("ResetPassword",view);
        }

        [HttpPost]
        public ActionResult ResetPassword(ResetPasswordPageView accountView)
        {
            var account = this.userService.GetAccountByCode(accountView.Code);
            if (account == null)
            {
                ModelState.AddModelError("", "重置失败，请重新申请重置密码");
                return View(accountView);
            }
            if (accountView.Password != accountView.ConfirmedPassword)
            {
                ModelState.AddModelError("", "密码不一致");
                return View(accountView);
            }
            account.Password = Md5Encrypt.HashPassword(accountView.ConfirmedPassword);
            this.userService.UpdateAccount(account);
            TempData["Message"] = "密码重置成功，请重新登录";
            return View(accountView);
        }

        [HttpPost]
        public ActionResult CheckAccount(string account)
        {
            if (Request.IsAjaxRequest())
            {
                if (!string.IsNullOrEmpty(account))
                {
                    var tmp = this.userService.GetAccount(account);
                    if (tmp != null)
                    {
                        return Content("True");
                    }
                    else
                    {
                        return Content("False");
                    }
                }
         
            }
            return View();
        }

        
        [HttpPost]
        public ActionResult CheckEmail(string email)
        {
            if (Request.IsAjaxRequest())
            {
                var account = this.userService.GetAccountByEmail(email);
                if (account != null)
                {
                    return Content("True");
                }
                else
                {
                    return Content("False");
                }
            }
            return View();
        }

    }
}
